package com.sinochem.sales.common.entity;

import com.sinochem.sales.common.enums.ResultEnum;

import java.io.Serializable;

/**
 * @author xuan😴🐶🐱🐽🌺  <a href="zhangshixuanj@163.com">联系作者</a>
 * @version Revision:v1.0,Date: 2018/4/16 11:01
 * @project cloud
 * @description 统一返回信息
 * @Modification Date: 2018/4/16 11:01  {填写修改说明}
 */
public class Result<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /*处理状态（1:成功、0：失败）*/
    private int success;

    /*错误消息*/
    private Error error;

    /*业务数据*/
    private T data;

    public Result() {
    }

    /*成功*/
    public Result(T data) {
        this.success = ResultEnum.SUCCESS.getCode();
        this.data = data;
        if (this.data == null) {
            this.data = (T) "";
        }
        error = null;
    }

    /*失败*/
    public Result(Error error) {
        this.success = ResultEnum.ERROR.getCode();
        this.error.setCode(error.getCode());
        this.error.setMsg(error.getMsg());
    }

    /*构造赋值*/
    public Result(int success, Error error, T data) {
        super();
        this.success = success;
        this.error = error;
        this.data = data;
    }

    /*返回成功状态*/
    public static <T> Result<T> success() {
        return new Result<T>(ResultEnum.SUCCESS.getCode(), null, null);
    }

    /*返回成功状态和业务数据*/
    public static <T> Result<T> success(T data) {
        return new Result<T>(ResultEnum.SUCCESS.getCode(), null, data);
    }

    /*返回失败状态*/
    public static <T> Result<T> error() {
        return new Result<T>(ResultEnum.ERROR.getCode(), null, null);
    }

    /*返回失败状态和错误消息*/
    public static <T> Result<T> error(String msg) {
        Error errorObj = new Error();
        errorObj.setMsg(msg);
        return new Result<T>(ResultEnum.ERROR.getCode(), errorObj, null);
    }

    /*返回失败状态和错误消息*/
    public static <T> Result<T> error(String errCode,String errMsg) {
        Error errorObj = new Error();
        errorObj.setCode(errCode);
        errorObj.setMsg(errMsg);
        return new Result<T>(ResultEnum.ERROR.getCode(), errorObj, null);
    }

    /*判断是否成功*/
    public boolean isSuccess() {
        return ResultEnum.SUCCESS.getCode() == this.success;
    }

    /*判断是否返回了业务数据*/
    public boolean hasData() {
        return (this.data != null);
    }


    public int getSuccess() {
        return success;
    }

    public Error getError() {
        return error;
    }

    public T getData() {
        return data;
    }

    public void setErrorCode(String errorCode) {
        this.error.setCode(errorCode);
    }

    public void setErrorMsg(String errorMsg) {
        this.error.setMsg(errorMsg);
    }

    public void setData(T data) {
        this.data = data;
    }

    public void setSuccess(int success) {
        this.success = success;
    }

    public void setError(Error error) {
        this.error = error;
    }

}
